﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IntoCommon.Util;
using Microsoft.VisualBasic.Logging;
using System.Windows.Media.Imaging;
using IntoStationSystem.Db;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.ObjectModel;
using IntoStationSystem.Global;
using System.Windows;

namespace IntoStationSystem.ViewModels
{
    public class PhotoDev
    {



        //型号
        public string ProModel = string.Empty;

        //载具id
        public string CraftId = string.Empty;

        //路径1
        public string PhotoUrl1 = string.Empty;

        //路径2
        public string PhotoUrl2 = string.Empty;
        /// <summary>
        /// 拍照次数
        /// </summary>
        public int PhotoNum = 0;

        //零件码
        public string PartCode = string.Empty;

        public void ShowPhoto()
        {
            try
            {
                //image.Source = null;
                PhotoNum++;
                //DbHelper.Log($"拍照次数{PhotoNum}");
                GC.Collect();
                GC.WaitForPendingFinalizers();

                string fileName = string.Empty;
                ObservableCollection<string> paths = new ObservableCollection<string>();
                ObservableCollection<string> newpaths = new ObservableCollection<string>();
                if (Fields.Station != "JZ")
                {
                    paths.Add(Path.Combine("D:\\CamearSaveImage", ProModel,
                    DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyyMMdd")));
                    newpaths.Add(Path.Combine("D:\\CamearNewSaveImage", ProModel,
                    DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyyMMdd")));
                }
                else
                {
                    paths.Add(Path.Combine("D:\\CamearSaveImage", ProModel, "CamearL",
                    DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyyMMdd")));
                    paths.Add(Path.Combine("D:\\CamearSaveImage", ProModel, "CamearR",
                    DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyyMMdd")));
                    newpaths.Add(Path.Combine("D:\\CamearNewSaveImage", ProModel, "CamearL",
                    DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyyMMdd")));
                    newpaths.Add(Path.Combine("D:\\CamearNewSaveImage", ProModel, "CamearR",
                    DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyyMMdd")));
                }

                for (int i = 0; i < paths.Count; i++)
                {
                    if (!Directory.Exists(paths[i]))
                    {

                        //DbHelper.Log($"{paths[i]}--路径不存在");
                        Locator.Instance.MainWindowVM.IsShowPhoto = true;
                        MessageBox.Show($"{paths[i]}--路径不存在");
                        PhotoNum--;
                        return;
                    }
                    if (!Directory.Exists(newpaths[i]))
                    {
                        //照片路径不存在创建路径
                        Directory.CreateDirectory(newpaths[i]);
                    }

                    var fileInfo = new DirectoryInfo(paths[i])
                                .GetFiles()
                                .Where(t => t.Extension.Equals(".jpg"))
                                .OrderByDescending(f => f.CreationTime).FirstOrDefault();


                    if (fileInfo == null)
                    {

                        DbHelper.Log($"未获取到照片：{fileInfo.FullName}");
                        Locator.Instance.MainWindowVM.IsShowPhoto = true;
                        PhotoNum--;
                        return;
                    }

                    string newFileName = Path.GetFileNameWithoutExtension(fileInfo.Name);
                    if (!string.IsNullOrEmpty(PartCode))
                        newFileName =PartCode.Replace("\n", "").Replace("\r", "").Trim();

                    var newFilePath = GetImageName(newpaths[i], newFileName, ".jpg");

                    DbHelper.Log($"获取照片时间：{DateTime.Now}");
                    using (Image originalImage = Image.FromFile(fileInfo.FullName))
                    {
                        Image compressedImage = CompressImage(originalImage, 500);
                        compressedImage.Save(newFilePath, GetEncoderInfo(compressedImage.RawFormat), null);
                    }
                    if (i == 0)
                    {
                        if (Fields.Station == "GP12" && PhotoNum % 2 == 0)
                        {

                            PhotoUrl2 = newFilePath;
                        }
                        else if ((Fields.Station == "GP12" && PhotoNum % 2 != 0)|| Fields.Station == "JZ")
                        {
                            PhotoUrl1 = newFilePath;
                            PhotoUrl2 ="";
                        }
                        else
                        {
                            PhotoUrl1 = newFilePath;
                            PhotoUrl2 = newFilePath;
                        }
                    }
                    else
                    {
                        PhotoUrl2 = newFilePath;
                    }
                    File.Delete(fileInfo.FullName);

                    //Log.Information(newFilePath);
                    //File.Move(fileInfo.FullName, newFilePath);

                    //Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss:fff")} : 切换拍照{newFilePath}");

                    
                    //Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss:fff")} : 切换照片完成");
                }
                DbHelper.Log("切换照片完成");
                //拍照显示，完成后回复2
                Locator.Instance.Service.ResponseCollection(3);
                
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss:fff")} : 切换照片错误 - {ex.Message}");
                //DbHelper.Log(ex, "显示照片");
                Locator.Instance.MainWindowVM.IsShowPhoto = true;
                PhotoNum--;
                DbHelper.Log($"切换照片失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="image"></param>
        /// <param name="maxSizeInKB"></param>
        /// <returns></returns>
        public Image CompressImage(Image image, long maxSizeInKB)
        {
            Image compressedImage = image;
            MemoryStream memoryStream = new MemoryStream();

            // 保存图片到内存流中，并在保存过程中调整压缩质量
            // 循环保存图片直到大小满足要求
            while (memoryStream.Length > 1024 * maxSizeInKB && memoryStream.Length > 0)
            {
                memoryStream.SetLength(0); // 清空内存流
                compressedImage.Save(memoryStream, GetEncoderInfo(compressedImage.RawFormat), null);

                // 重新加载内存流到Image对象，并调整压缩质量
                memoryStream.Seek(0, SeekOrigin.Begin);
                compressedImage = Image.FromStream(memoryStream);
            }

            return compressedImage;
        }

        private ImageCodecInfo GetEncoderInfo(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取新的图片名称
        /// </summary>
        /// <param name="path"></param>
        /// <param name="oldFileName"></param>
        /// <param name="fileExtension"></param>
        /// <returns></returns>
        private string GetImageName(string path, string oldFileName, string fileExtension)
        {
            // 查找现有文件名以 "ABC" 开头的文件
            var existingFiles = new DirectoryInfo(path)
                .GetFiles($"{oldFileName}*{fileExtension}")
                .Where(f => f.Name.StartsWith(oldFileName) && f.Extension == fileExtension)
                .Select(f => f.Name)
                .ToList();

            // 初始化新文件名
            string newFileName = oldFileName;
            int fileIndex = 1;  // 从 1 开始编号

            if (existingFiles.Count > 0)
            {
                // 查找已有文件名中最大编号
                foreach (var file in existingFiles)
                {
                    var match = Regex.Match(file, oldFileName + @"_(\d+)" + fileExtension);
                    if (match.Success && int.TryParse(match.Groups[1].Value, out int currentIndex))
                    {
                        fileIndex = Math.Max(fileIndex, currentIndex + 1);
                    }
                }

                // 使用下一个编号生成文件名
                newFileName = $"{oldFileName}_{fileIndex}";
            }

            // 生成新文件的完整路径
            string newFilePath = System.IO.Path.Combine(path, newFileName + fileExtension);
            return newFilePath;
        }
    }
}
